import axios from "axios";
import { async } from "q";
import { hospitalInfos } from "../components/network/getHospitalInfos";
export class Division {
  constructor() {
    this.provinces = null;
    this.cities = null;
    this.hospitals = null;
    this.init = this.getProvinces();
    this.initCity = this.getCities();

    this._selectProvinceName = "";
    this._selectCitiesName = "";
  }

  set selectCitiesName(newval) {
    this._selectCitiesName = newval;
    const that = this;
    (async function() {
      const { data } = await hospitalInfos.getHospitalNames({
        provinceName: that.selectProvinceName,
        cityName: that.selectCitiesName,
      });
      console.log(data);
      if (data?.length) {
        that.hospitalInfos = data;
      }
    })();
  }

  get selectCitiesName() {
    return this._selectCitiesName;
  }

  set selectProvinceName(newval) {
    this._selectProvinceName = newval;
    this.getCities();
  }

  get selectProvinceName() {
    return this._selectProvinceName;
  }

  get provinceNames() {
    if (this.provinces && this.provinces instanceof Array) {
      return this.provinces.map((item) => item.provinceName);
    }
  }

  get cityNames() {
    if (this.cities && this.cities instanceof Array) {
      return this.cities.map((item) => item?.cityName ?? item?.countyName);
    }
  }

  async getProvinces() {
    const { data } = await axios.get("proxy/getProvinces");
    if (data && data instanceof Array) {
      this.provinces = data;
    }
  }

  async getCities() {
    if (this.selectProvinceName) {
      const { data } = await axios.get(
        `proxy/getCities?province=${this.provincesMap.get(
          this.selectProvinceName
        )}`
      );
      if (data && data instanceof Array) {
        this.cities = data;
      }
    } else {
      return ["请选择省份"];
    }
  }

  get provincesMap() {
    const map = new Map();
    if (this.provinces && this.provinces instanceof Array) {
      for (const province of this.provinces) {
        map.set(province.provinceName, province.province);
      }
    }
    return map;
  }
}
